package com.yunhe.policyfulfillment.interceptor;

import com.alibaba.fastjson.JSON;
import com.yunhe.common.constant.SystemConsts;
import com.yunhe.common.exception.code.ErrorCode;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.util.StringUtil;
import com.yunhe.policyfulfillment.authority.model.CurrentUser;
import com.yunhe.policyfulfillment.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import com.yunhe.common.util.CollectionUtil;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @ClassName RequestInterceptor
 * @Description TODO
 * @Author HeTao
 * @Date 2021/7/21 15:34
 * @Version 1.0
 **/
@Component
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {


    /**
     * 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //获取请求头的token, 没有的化返回失败，前端需要登录
        //cors 跨域401 问题
        if(request.getMethod().equals(RequestMethod.OPTIONS.name())){
            response.setStatus(HttpStatus.OK.value());
            return true;
        }
        String token = request.getHeader(SystemConsts.HEADER.TOKEN.value());
        if (StringUtil.isEmpty(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            returnJson(response, JSON.toJSONString(new ResultObject<>(ErrorCode.CODE.LOGIN_EXPIRE.value(), "token lost")));
            return false;
        }
        //校验token，过期等原因失败则前端需要重新登录
        Map<String, String> map = JwtUtil.parseToken(token);
        if(CollectionUtil.isEmpty(map)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            returnJson(response, JSON.toJSONString(new ResultObject<>(ErrorCode.CODE.LOGIN_EXPIRE.value(), "token invalid")));
        }
        log.info("[Access-Token is ]:{}", token);
        log.info("[Request URL is ]:{}", request.getRequestURL());
        //将用户信息对象通过setAttribute放入Request中
        CurrentUser currentUser = new CurrentUser();
        currentUser.setUserId(map.get("userId"));
        currentUser.setUserName(map.get("userName"));
        request.setAttribute("currentUser", currentUser);

        return true;
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            log.error("拦截器返回JSON失败", e);
        } finally {
            if (writer != null){
                writer.close();
            }
        }
    }


    /**
     * 处理请求完成后视图渲染之前的处理操作
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 视图渲染之后的操作
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}
